package com.gcloud.mesh.asset.timer;

import java.util.Date;
import java.util.UUID;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import com.gcloud.framework.db.PageResult;
import com.gcloud.mesh.asset.service.IAssetService;
import com.gcloud.mesh.header.enums.MonitorMeter;
import com.gcloud.mesh.header.msg.asset.UpdateDatacenterMsg;
import com.gcloud.mesh.header.vo.asset.DatacenterItemVo;
import com.gcloud.mesh.header.vo.asset.DeviceItemVo;
import com.gcloud.mesh.monitor.dao.StatisticsDao;
import com.gcloud.mesh.monitor.entity.StatisticsEntity;
import com.gcloud.mesh.monitor.service.StatisticsCheatService;
import com.gcloud.mesh.monitor.service.StatisticsService;

import lombok.extern.slf4j.Slf4j;

@Slf4j
@Component
public class DatacenterPowerTimer {
	@Autowired
	private IAssetService assetService;

	@Autowired
	private StatisticsService statisticsService;
	
	@Autowired
	private StatisticsDao statisticsDao;

	@Autowired
	private StatisticsCheatService statisticsCheatService;

	@Scheduled(fixedDelay = 1000 * 60)
	public void work() {

		log.info("[EnvironmentPower] 计算数据中心动环能耗开始 START");

		PageResult<DatacenterItemVo> items = assetService.pageDatacenter(1, 999, "", "", "");

		for (DatacenterItemVo item : items.getList()) {

			String powerStr = statisticsCheatService.latestSample(MonitorMeter.DATACENTER_ENVIRONMENT_POWER.getMeter(),
					item.getId());

			if (!powerStr.isEmpty()) {
				Double power = Double.valueOf(powerStr);
				Double newPower = power;

				if (item.getPowerConservation() && item.getPower() > item.getThreshold()) {
					newPower = power * 0.8;
					log.info("[EnvironmentPower][{}] 原动环能耗={}，阈值={}, 节能后动环能耗={}", item.getId(), power,
							item.getThreshold(), newPower);
				}
				UpdateDatacenterMsg updateDatacenterMsg = new UpdateDatacenterMsg();
				updateDatacenterMsg.setId(item.getId());
				updateDatacenterMsg.setPower(newPower.intValue());
				assetService.updateDatacenter(updateDatacenterMsg, "");

				StatisticsEntity entity = new StatisticsEntity();
				entity.setId(UUID.randomUUID().toString());
				entity.setMeter("environment.power");
				entity.setResourceId(item.getId());
				entity.setTimestamp(new Date());
				entity.setValue(newPower);
				statisticsDao.save(entity);
			}
		}

		log.info("[EnvironmentPower] 计算数据中心动环能耗结束 END");
	}
}
